/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.dyn.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.cms.dyn.entity.CmsContentsDyn;
import com.jeeplus.modules.cms.dyn.service.CmsContentsDynService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 动态内容Controller
 * @author Sawyer
 * @version 2020-11-26
 */
@RestController
@RequestMapping(value = "/cms/dyn/cmsContentsDyn")
public class CmsContentsDynController extends BaseController {

	@Autowired
	private CmsContentsDynService cmsContentsDynService;

	@ModelAttribute
	public CmsContentsDyn get(@RequestParam(required=false) String id) {
		CmsContentsDyn entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = cmsContentsDynService.get(id);
		}
		if (entity == null){
			entity = new CmsContentsDyn();
		}
		return entity;
	}

	/**
	 * 动态内容列表数据
	 */
	@RequiresPermissions("cms:dyn:cmsContentsDyn:list")
	@GetMapping("list")
	public AjaxJson list(CmsContentsDyn cmsContentsDyn, HttpServletRequest request, HttpServletResponse response) {
		Page<CmsContentsDyn> page = cmsContentsDynService.findPage(new Page<CmsContentsDyn>(request, response), cmsContentsDyn);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取动态内容数据
	 */
	@RequiresPermissions(value={"cms:dyn:cmsContentsDyn:view","cms:dyn:cmsContentsDyn:add","cms:dyn:cmsContentsDyn:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(CmsContentsDyn cmsContentsDyn) {
		return AjaxJson.success().put("cmsContentsDyn", cmsContentsDyn);
	}

	/**
	 * 保存动态内容
	 */
	@RequiresPermissions(value={"cms:dyn:cmsContentsDyn:add","cms:dyn:cmsContentsDyn:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(CmsContentsDyn cmsContentsDyn, Model model) throws Exception{
		if (jeePlusProperites.isDemoMode()) {
			return AjaxJson.error("演示模式，不允许操作！");
		}
		String errMsg = beanValidator(cmsContentsDyn);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		cmsContentsDynService.save(cmsContentsDyn);
		return AjaxJson.success("保存动态内容成功");
	}


	/**
	 * 批量删除动态内容
	 */
	@RequiresPermissions("cms:dyn:cmsContentsDyn:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		if (jeePlusProperites.isDemoMode()) {
			return AjaxJson.error("演示模式，不允许操作！");
		}
		String[] idArray =ids.split(",");
		for(String id : idArray){
			cmsContentsDynService.delete(new CmsContentsDyn(id));
		}
		return AjaxJson.success("删除动态内容成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("cms:dyn:cmsContentsDyn:export")
    @GetMapping("export")
    public AjaxJson exportFile(CmsContentsDyn cmsContentsDyn, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "动态内容"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<CmsContentsDyn> page = cmsContentsDynService.findPage(new Page<CmsContentsDyn>(request, response, -1), cmsContentsDyn);
    		new ExportExcel("动态内容", CmsContentsDyn.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出动态内容记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("cms:dyn:cmsContentsDyn:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<CmsContentsDyn> list = ei.getDataList(CmsContentsDyn.class);
			for (CmsContentsDyn cmsContentsDyn : list){
				try{
					cmsContentsDynService.save(cmsContentsDyn);
					successNum++;
				} catch(Exception ex){
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条动态内容记录。");
			}

			return AjaxJson.success( "已成功导入 "+successNum+" 条动态内容记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入动态内容失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入动态内容数据模板
	 */
	@RequiresPermissions("cms:dyn:cmsContentsDyn:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "动态内容数据导入模板.xlsx";
    		List<CmsContentsDyn> list = Lists.newArrayList();
    		new ExportExcel("动态内容数据", CmsContentsDyn.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }


}
